package cn.schoolwow.util.test.module.query.jsonarray.flow.group;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.jsonarray.QueryJSONArray;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Assert;

import java.util.List;

public class JSONQueryGroupByFieldFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        JSONArray userArray = (JSONArray) flowContext.checkData("userArray");
        String password = (String) flowContext.checkData("password");
        List<String> roleNameList = (List<String>) flowContext.checkData("roleNameList");

        JSONObject roleNameUserListMap = QueryJSONArray.newQuery(userArray)
                .addQuery("password", password)
                .execute()
                .groupByFieldName("roleName");
        Assert.assertEquals(roleNameList.size(), roleNameUserListMap.size());
        for(String roleName:roleNameUserListMap.keySet()){
            JSONArray singleRoleNameUserArray = roleNameUserListMap.getJSONArray(roleName);
            for(int i=0;i<singleRoleNameUserArray.size();i++){
                JSONObject user = singleRoleNameUserArray.getJSONObject(i);
                Assert.assertEquals(roleName, user.getString("roleName"));
            }
            Assert.assertEquals(userArray.size()/2, singleRoleNameUserArray.size());
        }
    }

    @Override
    public String name() {
        return "根据指定字段分组";
    }
}
